import router from "@/router";
import { userLoginUserStore } from "@/store/user";
import AccessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  const loginUserStore = userLoginUserStore();
  let loginUser = loginUserStore.loginUser;
  if (to.fullPath != "/") {
    if (!loginUser || !loginUser.userRole) {
      await loginUserStore.fetchLoginUser();
      loginUser = loginUserStore.loginUser;
    }
  }
  //当前页面需要的权限
  const needAccess = to.meta?.access ?? AccessEnum.NOT_LOGIN;
  //要去的页面必须登录
  if (needAccess !== AccessEnum.NOT_LOGIN) {
    //如果没登陆跳转到登录页，loginUser.userRole中的userRole是后端返回的数据
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === AccessEnum.NOT_LOGIN
    ) {
      next(`/user/login?redirect=${to.fullPath}`);
    }
    //如果登录l，判断权限是否足够，如果不足，跳转到无权限页面
    if (!checkAccess(loginUser, needAccess)) {
      next(`/noAuth`);
      return;
    }
  }
  next();
});
